package Sl;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

public class Sl05 {
    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, TransformerException {
        //得到DOM解析器的工厂
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
        //从DOM工厂获得DOM解析器
        DocumentBuilder db=dbf.newDocumentBuilder();
        //解析XML文档，得到一个Document对象，即DOM树
        Document doc=db.parse("src/main/java/Sl/Sj02.xml");//收藏信息.xml为保存手机收藏信息的xml文档
        //得到所有Brand节点列表信息
        NodeList list=doc.getElementsByTagName("Brand");
        for (int i=0;i<list.getLength();i++){
            Element brandElement=(Element) list.item(i);
            String brandName=brandElement.getAttribute("name");
            if (brandName.equals("三星")){
                brandElement.setAttribute("name","SAMSUNG"); //修改属性
            }
        }
       //保存XML文件
        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        Transformer transformer=transformerFactory.newTransformer();
        DOMSource domSource=new DOMSource(doc);
        //设置编码类型
        transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");
        StreamResult result=new StreamResult(new FileOutputStream("src/main/java/Sl/Sj02.xml"));
        //把DOM树转换为XML文件
        transformer.transform(domSource,result);
    }
}
